package com.sskj.aikeeper.hangqing.fragment;

import android.annotation.SuppressLint;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.aikeeper.R;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.lib.SpApplication;
import com.sskj.aikeeper.bean.BannerNoticeBean;
import com.sskj.aikeeper.component.DaggerUserDataComponent;
import com.sskj.aikeeper.presenter.HomePresenter;
import com.sskj.common.base.App;
import com.sskj.common.box.imageloader.GlideImageLoader;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.common.util.SPUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.widget.TipDialog;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @author Hey
 * Create at  2019/06/25
 */
@Route(path = RConfig.APP_FRAGMENT_HOME)
public class HomeFragment extends BaseFragment<HomePresenter> {
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.iv_title_logo)
    ImageView ivTitleLogo;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.recyclerView_top)
    RecyclerView topList;
    @BindView(R.id.constraint_sing_in)
    ConstraintLayout constraintSingIn;
    @BindView(R.id.constraint_rotary_table)
    ConstraintLayout constraintRotaryTable;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @BindView(R.id.smartRefreshView)
    SmartRefreshLayout smartRefreshView;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    private Disposable noticeDispo;
    private BannerNoticeBean.ArticleBean noticeBean;

    private List<CoinBean> topCoins = new ArrayList<>();
    private BaseAdapter<CoinBean> topAdapter;
    private List<BannerNoticeBean.BannerBean> bannerList;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_home;
    }

    @Override
    public HomePresenter getPresenter() {
        return new HomePresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        ImageUtil.setImage(R.mipmap.icon_head, ivHead);

        if (Constans.LANGUAGE_EN.equals(SPUtil.get(SPConfig.LANGUAGE, Constans.LANGUAGE_CNA))) {
            ImageUtil.setImage(R.mipmap.icon_logo_english, ivTitleLogo);
        } else if (Constans.LANGUAGE_CNA.equals(SPUtil.get(SPConfig.LANGUAGE, Constans.LANGUAGE_CNA))) {
            ImageUtil.setImage(R.mipmap.icon_logo_cn, ivTitleLogo);
        } else if (Constans.LANGUAGE_TRA.equals(SPUtil.get(SPConfig.LANGUAGE, Constans.LANGUAGE_CNA))) {
            ImageUtil.setImage(R.mipmap.icon_logo_cn, ivTitleLogo);
        }

        banner.setImageLoader(new GlideImageLoader());

        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayout, (Fragment) ARouter.getInstance().build(RConfig.APP_FRAGMENT_COIN_LIST).navigation())
                .commitAllowingStateLoss();

        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.lib_646));
            return textView;
        });


        topList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        topCoins.add(new CoinBean("BTC", "BTC/USDT"));
        topCoins.add(new CoinBean("ETH", "ETH/USDT"));
        topCoins.add(new CoinBean("AICASH", "AICASH/USDT"));
        topAdapter = new BaseAdapter<CoinBean>(R.layout.app_item_home_top, topCoins, topList) {
            @Override
            public void bind(ViewHolder holder, CoinBean item) {
                holder.setText(R.id.name, item.getCode())
                        .setText(R.id.price, NumberUtil.keep2(item.getPrice()))
                        .setText(R.id.changeRate, item.getChangeRate())
                        .setText(R.id.cnyPrice, String.format("≈%s CNY", CommonUtil.dealCNY(item.getCnyPrice())));
                if (Double.valueOf(item.getChange()) >= 0) {
                    holder.setTextColor(R.id.price, ContextCompat.getColor(App.INSTANCE, R.color.libUpColor));
                    holder.setTextColor(R.id.changeRate, ContextCompat.getColor(App.INSTANCE, R.color.libUpColor));
                } else {
                    holder.setTextColor(R.id.price, ContextCompat.getColor(App.INSTANCE, R.color.libDownColor));
                    holder.setTextColor(R.id.changeRate, ContextCompat.getColor(App.INSTANCE, R.color.libDownColor));
                }
            }
        };
        ItemClickSupport.addTo(topList).setOnItemClickListener((recyclerView, position, v) -> ARouter.getInstance().build(RConfig.APP_ACTIVITY_CHART)
                .withSerializable(Constans.COIN_BEAN, topAdapter.getData().get(position))
                .withString(Constans.COIN_CODE, topAdapter.getData().get(position).getCode())
                .navigation());

    }

    @Override
    public void initData() {
        mPresenter.getTopData(true);
        mPresenter.getHangqingData();
        smartRefreshView.setOnRefreshListener(refreshLayout -> mPresenter.getTopData(false));
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                ImageUtil.setCircleImage(BaseHttpConfig.BASE_URL + userData.getUpic(), ivHead);
            } else {
                userData = null;
            }
        });
        ClickUtil.click(300, ivHead, () -> {
            RxBus.getDefault().send(RxBusCode.DRAWER_OPEN);
        });
        //签到
        ClickUtil.click(300, constraintSingIn, () -> {
            if (checkCetification()) {
                ARouter.getInstance().build(RConfig.APP_ACTIVITY_SIGNIN).navigation();
            }
        });
        //公告
        ClickUtil.click(300, tvMore, () -> {
            ARouter.getInstance().build(RConfig.COMMUNITY_ACTIVITY_GONGGAO).navigation();
        });
        //转盘
        ClickUtil.click(300, constraintRotaryTable, () -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(BaseHttpConfig.ZHUANPAN);
            stringBuilder.append("?token=");
            stringBuilder.append(SPUtil.get(SPConfig.TOKEN, ""));
            stringBuilder.append("?account=");
            stringBuilder.append(SPUtil.get(SPConfig.ACCOUNT, ""));
            stringBuilder.append("?lang=");

            if (Constans.LANGUAGE_EN.equals(SPUtil.get(SPConfig.LANGUAGE, Constans.LANGUAGE_CNA))) {
                stringBuilder.append("EN");
            } else if (Constans.LANGUAGE_CNA.equals(SPUtil.get(SPConfig.LANGUAGE, Constans.LANGUAGE_CNA))) {
                stringBuilder.append("CN");
            } else if (Constans.LANGUAGE_TRA.equals(SPUtil.get(SPConfig.LANGUAGE, Constans.LANGUAGE_CNA))) {
                stringBuilder.append("TW");
            }


            if (checkCetification()) {
                ARouter.getInstance().build(RConfig.APP_ACTIVITY_ZHUANPAN)
                        .withString(Constans.TITLE, App.INSTANCE.getString(R.string.app_homeFragment1))
                        .withString(Constans.WEB_URL, stringBuilder.toString())
                        .navigation();
//                        .withString(Constans.WEB_URL, BaseHttpConfig.ZHUANPAN
//                        + "?token=" + SPUtil.get(SPConfig.TOKEN, "")
//                        + "?account=" + SPUtil.get(SPConfig.ACCOUNT, "")
//                        + "?lang=CN")
            }
        });
    }

    @SuppressLint("CheckResult")
    public void getTopDataOK(BannerNoticeBean data) {
        if (data == null) {
            return;
        }
        bannerList = data.getBanner();
        Observable.fromArray(data.getBanner())
                .map(bannerBeans -> {
                    List<String> imgUrls = new ArrayList<>();
                    for (int i = 0; i < bannerBeans.size(); i++) {
                        imgUrls.add(bannerBeans.get(i).getBanner_url());
                    }
                    return imgUrls;
                }).compose(RxSchedulersHelper.io_main())
                .subscribe(strings -> {
                    if (this.banner != null) {
                        this.banner.setImages(strings);
                        this.banner.start();
                    }
                });

        if (tvNotice != null) {
            if (data.getArticle().size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeBean = data.getArticle().get((int) (i % data.getArticle().size()));
                                tvNotice.setText(noticeBean.getTitle());
                                ClickUtil.click(tvNotice, () -> {
                                    ARouter.getInstance().build(RConfig.COMMUNITY_ACTIVITY_PUBLISH_ARTICLE)
                                            .withString("id", noticeBean.getId())
                                            .navigation();
                                });
                            }
                        }, System.out::println);
            }
        }
    }

    @SuppressLint("CheckResult")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(CoinBean coinBean) {
        if (topAdapter != null) {
            Flowable.fromIterable(topAdapter.getData())
                    .compose(RxSchedulersHelper.transformer())
                    .subscribe(item -> {
                        if (coinBean.getCode().equals(item.getCode())) {
                            int index = topAdapter.getData().indexOf(item);
                            if (index != -1) {
                                topAdapter.getData().set(index, coinBean);
                                topAdapter.notifyItemChanged(index, 1);
                            }
                        }
                    }, e -> e.printStackTrace());
        }
    }

    @SuppressLint("CheckResult")
    public void getHangqingDataOK(List<CoinBean> data) {
        if (data == null) {
            return;
        }
        if (topAdapter != null) {
            Flowable.fromIterable(topAdapter.getData())
                    .compose(RxSchedulersHelper.transformer())
                    .subscribe(item -> {
                        for (int i = 0; i < data.size(); i++) {
                            if (data.get(i).getCode().equals(item.getCode())) {
                                int index = topAdapter.getData().indexOf(item);
                                if (index != -1) {
                                    topAdapter.getData().set(index, data.get(i));
                                    topAdapter.notifyItemChanged(index, 1);
                                }
                            }
                        }
                    }, e -> e.printStackTrace());
        }
    }

    private boolean checkLogin() {
        if (userData == null) {
            new TipDialog(getActivity())
                    .setTitleText(App.INSTANCE.getString(R.string.app_homeFragment2))
                    .setContentText(App.INSTANCE.getString(R.string.app_homeFragment3))
                    .setListener(dialog -> ARouter.getInstance().build(RConfig.APP_LOGIN_NUMBER).navigation())
                    .show();
            return false;
        }
        return true;
    }

    public void stopRefresh() {
        if (smartRefreshView != null) {
            smartRefreshView.finishRefresh();
        }
    }
}
